import datetime
import time

import smbus


def set_rtc_time(tim: datetime.datetime):
    # tim = datetime.datetime.now()
    print('当前时间：%s' % tim.strftime('%Y-%d-%m %H:%M:%S'))
    wbuf = [
        ((int(tim.second / 10) << 4) | (tim.second % 10)),
        ((int(tim.minute / 10) << 4) | (tim.minute % 10)),
        ((int(tim.hour / 10) << 4) | (tim.hour % 10)) & 0x3f,
        (tim.weekday() + 1) & 0x07,
        ((int(tim.day / 10) << 4) | (tim.day % 10)) & 0x3F,
        ((int(tim.month / 10) << 4) | (tim.month % 10)) & 0x1F,
        ((int((tim.year - 2000) / 10) << 4) | ((tim.year - 2000) % 10))
    ]
    iic = smbus.SMBus(1)
    iic.write_i2c_block_data(0x68, 0, wbuf)
    time.sleep(0.2)


def get_rtc_time() -> datetime.datetime:
    iic = smbus.SMBus(1)
    rbuf = iic.read_i2c_block_data(0x68, 0, 7)
    sec = (rbuf[0] >> 4 & 0x0f) * 10 + (rbuf[0] & 0x0f)
    minute = (rbuf[1] >> 4 & 0x0f) * 10 + (rbuf[1] & 0x0f)
    hour = (rbuf[2] >> 4 & 0x03) * 10 + (rbuf[2] & 0x0f)
    wday = rbuf[3] & 0x0f - 1
    day = (rbuf[4] >> 4 & 0x03) * 10 + (rbuf[4] & 0x0f)
    mon = (rbuf[5] >> 4 & 0x01) * 10 + (rbuf[5] & 0x0f)
    year = (rbuf[6] >> 4 & 0x0f) * 10 + (rbuf[6] & 0x0f) + 2000
    return datetime.datetime(year, mon, day, hour, minute, sec)


tim = datetime.datetime.now()
wts = tim.strftime('%Y-%d-%m %H:%M:%S')
print('当前时间：%s' % wts)
print('系统时间写入RTC。')
set_rtc_time(tim)
print('从RTC读取时间。')
rtim = get_rtc_time()
rts = rtim.strftime('%Y-%d-%m %H:%M:%S')
print('RTC时间：%s' % rts)

if wts == rts:
    print('RTC测试成功。')
else:
    print('RTC测试失败。')
